package com.bw.risk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.core.creditStatus.AuthenStatus;
import com.bw.core.creditStatus.DeleteStatus;
import com.bw.core.creditStatus.RiskStatus;
import com.bw.core.vo.OrderRiskVO;
import com.bw.core.vo.RiskOrderVO;
import com.bw.core.vo.UserVo;
import com.bw.risk.feginClient.UserFeignService;
import com.bw.risk.mapper.TbRiskBlackMapper;
import com.bw.risk.mapper.TbRiskLogMapper;
import com.bw.risk.mapper.TbRiskWhiteMapper;
import com.bw.risk.pojo.TbRiskBlack;
import com.bw.risk.pojo.TbRiskLog;
import com.bw.risk.pojo.TbRiskOrder;
import com.bw.risk.mapper.TbRiskOrderMapper;
import com.bw.risk.pojo.TbRiskWhite;
import com.bw.risk.service.TbRiskOrderService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 风控审核表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
public class TbRiskOrderServiceImpl extends ServiceImpl<TbRiskOrderMapper, TbRiskOrder> implements TbRiskOrderService {

    @Autowired
    private TbRiskOrderMapper riskOrderMapper;

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private TbRiskWhiteMapper riskWhiteMapper;

    @Autowired
    private TbRiskBlackMapper riskBlackMapper;

    @Autowired
    private TbRiskLogMapper riskLogMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    //用户各项条件判断
    @Override
    public void riskSystem(TbRiskOrder riskOrder) {

        //将原先的订单状态改为审核中
        riskOrder.setStatus(RiskStatus.RISK_CHECK_RUNNING);
        riskOrderMapper.updateById(riskOrder);


        //获取用户信息

        UserVo userVo = userFeignService.findUserMessage(riskOrder.getUserId());

        //白名单认证
        QueryWrapper<TbRiskWhite> riskWhiteQueryWrapper = Wrappers.query();
        riskWhiteQueryWrapper.eq("user_id", userVo.getId()).eq("is_delete", DeleteStatus.NOT_DELETE);
        List<TbRiskWhite> riskWhites = riskWhiteMapper.selectList(riskWhiteQueryWrapper);
        if (CollectionUtil.isNotEmpty(riskWhites)) { //直接放款
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("此用户在白名单中");
            riskOrder.setUpdateTime(new Date());
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "此用户在白名单中");
            return;
        }

        //黑名单认证
        QueryWrapper<TbRiskBlack> riskBlackQueryWrapper = Wrappers.query();
        riskBlackQueryWrapper.eq("user_id", userVo.getId()).eq("is_delete", DeleteStatus.NOT_DELETE);
        List<TbRiskBlack> riskBlacks = riskBlackMapper.selectList(riskBlackQueryWrapper);
        if (CollectionUtil.isNotEmpty(riskBlacks)) { //直接拒绝
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);//审核失败
            riskOrder.setRiskMsg("此用户在黑名单中");
            riskOrder.setUpdateTime(new Date());
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "此用户在黑名单中");
            return;
        }

        //身份认证认证
        if (userVo.getIsIdentity() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("身份认证未完成");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "身份认证未完成");
            return;
        }
        if (userVo.getIsIdentity() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("身份认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "身份认证完成");
        }


        //银行卡认证
        if (userVo.getIsBankCard() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("银行卡未认证");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "银行卡未完成");
            return;
        }
        if (userVo.getIsBankCard() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("银行卡认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "银行卡认证完成");
        }


        //联系人认证
        if (userVo.getIsLinkman() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("联系人未认证");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "联系人未认证");
            return;
        }
        if (userVo.getIsLinkman() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("联系人认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "联系人认证完成");
        }


        //通讯录认证
        if (userVo.getIsContacts() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("通讯录未认证");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "通讯录未认证");
            return;
        }
        if (userVo.getIsContacts() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("通讯录认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "通讯录认证完成");
        }

        //运营商认证
        if (userVo.getIsOperator() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("运营商未认证");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "运营商未认证");
            return;
        }
        if (userVo.getIsOperator() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("运营商认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "运营商认证完成");
        }

        //淘宝认证
        if (userVo.getIsTaobao() == AuthenStatus.NOT_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("淘宝未认证");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder, "淘宝未认证");
            return;
        }
        if (userVo.getIsTaobao() == AuthenStatus.IS_AUTHEN) {
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
            riskOrder.setRiskMsg("淘宝认证完成");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder, "淘宝认证完成");
        }


        //通讯录里是否有黑名单
        List<String> callBook = userFeignService.findCallBook(riskOrder.getUserId());
        for (String callbook : callBook) {
            riskBlackQueryWrapper.eq("user_phone", callbook).eq("is_delete", DeleteStatus.NOT_DELETE);
            List<TbRiskBlack> riskBlackCall = riskBlackMapper.selectList(riskBlackQueryWrapper);
            if (CollectionUtil.isNotEmpty(riskBlackCall)){
                riskOrder.setRiskMsg("用户通讯录中有黑名单人员");
                riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
                riskOrderMapper.updateById(riskOrder);
                refuse(riskOrder,"用户通讯录中有黑名单人员");
                return;
            }else {
                riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
                riskOrder.setRiskMsg("用户通讯录中没有黑名单人员");
                riskOrderMapper.updateById(riskOrder);
                success(riskOrder,"用户通讯录中没有黑名单人员");
            }
        }



        //判断联系人中的黑名单记录
        List<String> linkManPhone = userFeignService.findLinkMan(riskOrder.getUserId());
        for (String linkman : linkManPhone) {
            riskBlackQueryWrapper.eq("user_phone", linkman).eq("is_delete", DeleteStatus.NOT_DELETE);
            List<TbRiskBlack> riskBlackCall = riskBlackMapper.selectList(riskBlackQueryWrapper);
            if (CollectionUtil.isNotEmpty(riskBlackCall)){
                riskOrder.setRiskMsg("用户联系人中有黑名单人员");
                riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
                riskOrderMapper.updateById(riskOrder);
                refuse(riskOrder,"用户联系人中有黑名单人员");
                return;
            }else {
                riskOrder.setRiskMsg("用户联系人中没有黑名单人员");
                riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);//审核成功
                riskOrderMapper.updateById(riskOrder);
                success(riskOrder,"用户联系人中没有黑名单人员");
            }
        }


        //验证运营商
        String operator = userFeignService.findOperator(riskOrder.getUserId());
        JSONObject operatorObject = JSONObject.parseObject(operator);
        JSONObject operatorData = operatorObject.getJSONObject("data");
        JSONObject res_data = operatorData.getJSONObject("res_data");
        JSONArray billdata = res_data.getJSONArray("billdata");

//        int consumption  = 0;//消费水平
        BigDecimal consumption = new BigDecimal(0);

        for (int i=0; i<billdata.size();i++){
            JSONObject jsonObject1 = billdata.getJSONObject(i);
            String call_pay = jsonObject1.getString("call_pay");
            BigDecimal callNum = BigDecimal.valueOf(Integer.parseInt(call_pay));
            consumption = consumption.add(callNum);
        }
        BigDecimal jun = consumption.divide(BigDecimal.valueOf(billdata.size()));
        BigDecimal guzhi = new BigDecimal(50);
        if(jun.compareTo(guzhi)==0){
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("不满足贷款要求");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder,"不满足贷款要求");
            return;
        }
        else{
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);
            riskOrder.setRiskMsg("满足贷款需求");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder,"满足贷款需求");
        }



        //淘宝数据
        String taoBao = userFeignService.findTaoBao(riskOrder.getUserId());
        JSONObject taoBaoObject1 = JSONObject.parseObject(taoBao);
        JSONObject taoBaoData = taoBaoObject1.getJSONObject("data");
        Integer jiebei = taoBaoData.getJSONObject("res_data").getInteger("jiebeiAmount");
        if(jiebei<2000){
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setRiskMsg("借呗额度不够");
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder,"借呗额度不够");
            return;
        }
        if(jiebei>2000){
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);
            riskOrder.setRiskMsg("借呗额度满足");
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder,"借呗额度满足");
        }



        //机器分数
        Integer num = RandomUtil.randomInt(50, 100);
        double core = num.doubleValue();
        if (core<60){
            riskOrder.setRiskScore(core);
            riskOrder.setRiskMsg("审核分数较低");
            riskOrder.setStatus(RiskStatus.RISK_CHECK_REFUSE);
            riskOrder.setUpdateTime(new Date());
            riskOrderMapper.updateById(riskOrder);
            refuse(riskOrder,"审核失败");
            return;
        }
        if (core>60){
            riskOrder.setRiskScore(core);
            riskOrder.setRiskMsg("审核分数符合");
            riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);
            riskOrder.setUpdateTime(new Date());
            riskOrderMapper.updateById(riskOrder);
            success(riskOrder,"审核分数符合");
        }

        //修改最后的状态
        riskOrder.setRiskMsg("各项数据都达标，审核成功");
        riskOrder.setStatus(RiskStatus.RISK_CHECK_SUCCESS);
        riskOrder.setUpdateTime(new Date());
        riskOrderMapper.updateById(riskOrder);
        success(riskOrder,"各项数据都达标，审核成功");

    }

    
        //拒绝原因
        public void refuse (TbRiskOrder riskOrder, String riskMsg){
            TbRiskLog riskLog = new TbRiskLog();
            riskLog.setRiskNo(riskOrder.getRiskNo());
            riskLog.setUserId(riskOrder.getUserId());
            riskLog.setUserName(riskOrder.getUserName());
            riskLog.setRiskStatus(riskOrder.getStatus());
            riskLog.setRiskDesc(riskMsg);
            riskLog.setRemart(riskMsg);
            riskLog.setRiskTime(riskOrder.getCreateTime());
            riskLog.setCreateTime(new Date());
            riskLog.setUpdateTime(new Date());
            riskLog.setIsDelete(DeleteStatus.NOT_DELETE);
            riskLogMapper.insert(riskLog);

            RiskOrderVO riskOrderVO = new RiskOrderVO();
            riskOrderVO.setOrderNo(riskOrder.getOrderNo());
            riskOrderVO.setStatus(riskLog.getRiskStatus());//失败
            riskOrderVO.setRiskMsg(riskLog.getRiskDesc());
            String toJSONString = JSONObject.toJSONString(riskOrderVO);
            amqpTemplate.convertAndSend("item_cheng",toJSONString);

        }
        //成功原因
        public void success (TbRiskOrder riskOrder, String riskMsg){
            TbRiskLog riskLog = new TbRiskLog();
            riskLog.setRiskNo(riskOrder.getRiskNo());
            riskLog.setUserId(riskOrder.getUserId());
            riskLog.setUserName(riskOrder.getUserName());
            riskLog.setRiskTime(riskOrder.getCreateTime());
            riskLog.setCreateTime(new Date());
            riskLog.setUpdateTime(new Date());
            riskLog.setIsDelete(riskOrder.getIsDelete());
            riskLog.setRiskStatus(RiskStatus.RISK_CHECK_SUCCESS);
            riskLog.setRiskDesc(riskMsg);
            riskLog.setRemart(riskMsg);
            riskLog.setRiskTime(new Date());
            riskLogMapper.insert(riskLog);

            RiskOrderVO riskOrderVO = new RiskOrderVO();
            riskOrderVO.setOrderNo(riskOrder.getOrderNo());
            riskOrderVO.setStatus(riskLog.getRiskStatus());//成功
            riskOrderVO.setRiskMsg(riskLog.getRiskDesc());
            String toJSONString = JSONObject.toJSONString(riskOrderVO);
            amqpTemplate.convertAndSend("item_cheng",toJSONString);

        }
}


